package com.kitom.qqmap.api.impl;

import com.kitom.qqmap.api.QQmapGeocodeService;
import com.kitom.qqmap.api.QQmapService;
import com.kitom.qqmap.bean.address.QQmapAddrToGeoRequest;
import com.kitom.qqmap.bean.address.QQmapAddrToGeoResult;
import com.kitom.qqmap.bean.geocode.QQmapGeocodeGeoRequest;
import com.kitom.qqmap.bean.geocode.QQmapGeocodeGeoResult;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;

/**
 * <pre>
 *  地理编码服务接口实现
 * </pre>
 * @author <a href="https://gitee.com/kitom">ki_tom</a>
 * @since 2021-01-12
 */
@AllArgsConstructor
public class QQmapGeocodeServiceImpl implements QQmapGeocodeService {

    private QQmapService amapService;

    @Override
    public QQmapGeocodeGeoResult geocodeGeo(QQmapGeocodeGeoRequest amapGeocodeGeoRequest) {
        String result = this.amapService.get(REGEO,amapGeocodeGeoRequest.toJson());
        QQmapGeocodeGeoResult qQmapGeocodeGeoResult = JSONUtil.toBean(result, QQmapGeocodeGeoResult.class);
        /**
         * {
         *     "message": "此key每秒请求量已达到上限",
         *     "status": 120
         * }
         * 线程暂停1s后重新发起请求
         */
        Integer status = qQmapGeocodeGeoResult.getStatus();
        if(status ==120){
            try {
                System.out.println("lbs每秒请求量已达到上限,休眠1s后重新调用");
                Thread.sleep(1200);
                System.out.println("lbs每秒请求量已达到上限,休眠完成");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            result = this.amapService.get(REGEO,amapGeocodeGeoRequest.toJson());
            qQmapGeocodeGeoResult = JSONUtil.toBean(result, QQmapGeocodeGeoResult.class);
        }
        if(status ==121){
            throw new RuntimeException("lbs当日请求量已达到上限");
        }
        return qQmapGeocodeGeoResult;
    }

    @Override
    public QQmapAddrToGeoResult addrToGeocode(QQmapAddrToGeoRequest qmapAddrToGeoRequest) {
        String result = this.amapService.get(GEO,qmapAddrToGeoRequest.toJson());
        QQmapAddrToGeoResult qQmapAddrToGeoResult = JSONUtil.toBean(result, QQmapAddrToGeoResult.class);
        /**
         * {
         *     "message": "此key每秒请求量已达到上限",
         *     "status": 120
         * }
         * 线程暂停1s后重新发起请求
         */
        Integer status = qQmapAddrToGeoResult.getStatus();
        if(status ==120){
            try {
                System.out.println("lbs每秒请求量已达到上限,休眠1s后重新调用");
                Thread.sleep(1200);
                System.out.println("lbs每秒请求量已达到上限,休眠完成");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            result = this.amapService.get(GEO,qmapAddrToGeoRequest.toJson());
            qQmapAddrToGeoResult = JSONUtil.toBean(result, QQmapAddrToGeoResult.class);
        }
        if(status ==121){
            throw new RuntimeException("lbs当日请求量已达到上限");
        }
        return qQmapAddrToGeoResult;
    }
}